package com.ytmz.gateway.security;

import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 鉴权认证
 *
 * @author Chill
 */
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
    private SecurityProperties securityProperties;
    private TokenProvider tokenProvider;
    private AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (isSkip(path)) {
            return chain.filter(exchange);
        }
        ServerHttpResponse resp = exchange.getResponse();
        String headerToken = getToken(exchange);
        if (StringUtils.isBlank(headerToken)) {
            return unAuth(resp, "缺失令牌,鉴权失败");
        }
        if (StringUtils.isEmpty(headerToken)) {
            return unAuth(resp, "缺失令牌,鉴权失败");
        }
        if (!tokenProvider.validateToken(headerToken)) {
            return unAuth(resp, "令牌认证失败");
        }
        return chain.filter(exchange);
    }

    private String getToken(ServerWebExchange exchange) {
        return AuthHelp.getTokenString(exchange, securityProperties);
    }

    private boolean isSkip(String path) {
        if (authProperties.getSkipUrl().contains(path)) {
            return true;
        }
        return AuthProvider.getDefaultSkipUrl().stream()
                .map(url -> url.replace(AuthProvider.TARGET, AuthProvider.REPLACEMENT)).anyMatch(path::contains);
    }

    private Mono<Void> unAuth(ServerHttpResponse resp, String msg) {
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        DataBuffer buffer = resp.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }

}
